package com.cmq.web_1.user_register;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.regex.Pattern;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String EMAIL_REGEX = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
    private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String contextPath = request.getContextPath(); // 获取项目上下文（如：/cmq_web_1）

        // 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        // 验证逻辑
        boolean isValid = true;
        StringBuilder errorMsg = new StringBuilder();

        if (username == null || username.trim().isEmpty()) {
            isValid = false;
            errorMsg.append("用户名不能为空<br>");
        }
        if (password == null || password.trim().isEmpty()) {
            isValid = false;
            errorMsg.append("密码不能为空<br>");
        } else if (password.length() < 6) {
            isValid = false;
            errorMsg.append("密码长度不能少于6个字符<br>");
        }
        if (email == null || email.trim().isEmpty()) {
            isValid = false;
            errorMsg.append("邮箱不能为空<br>");
        } else if (!EMAIL_PATTERN.matcher(email).matches()) {
            isValid = false;
            errorMsg.append("邮箱格式不正确<br>");
        }
        if (UserStorage.isUsernameExists(username)) {
            isValid = false;
            errorMsg.append("用户名已被注册<br>");
        }

        if (isValid) {
            // 注册成功：创建用户并设置Session（自动登录）
            User user = new User(username, password, email);
            UserStorage.addUser(user);
            HttpSession session = request.getSession();
            session.setAttribute("user", user); // 关键：存储登录状态

            // 转发到success.jsp（带用户信息）
            request.setAttribute("user", user);
            request.getRequestDispatcher("/user-register/success.jsp").forward(request, response);
        } else {
            // 注册失败：转发到failure.jsp（带错误信息）
            request.setAttribute("errorMessage", errorMsg.toString());
            request.getRequestDispatcher("/user-register/failure.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 重定向到注册页面（带上下文路径）
        response.sendRedirect(request.getContextPath() + "/user-register/register.jsp");
    }
}